<script lang="ts" setup>
import { apiRole } from "@/api/sys";
import { useMessage } from "@/hooks/web/use-message";
import { type Form, type RoleInfo } from "@/models";
import { reactive, ref } from "vue";
import { type VxeFormProps, type VxeFormInstance, type VxeModalInstance, type VxeModalProps, type VxeModalListeners } from "vxe-table";
import MenuPicker from "@/components/menu-picker.vue";
import Avatar from "~icons/ep/avatar";
import Checked from "~icons/ep/checked";
import Tools from "~icons/ep/tools";

//#region [state]
type PageState = { title: string; show: boolean; step: number; value?: RoleInfo };
const page = reactive<PageState>({ title: "新增角色", show: false, step: 0 });
const emit = defineEmits<{ (event: "onsaved", value?: Nullable<number>): void }>();
const { createMessage } = useMessage();
//#endregion

//#region [modal]
const modalRef = ref<VxeModalInstance>();
const modalProps = reactive<VxeModalProps>({
  resize: true,
  destroyOnClose: true,
  escClosable: true,
  showFooter: true,
  width: 900,
  height: 600,
  position: { top: window.innerHeight * 0.2 },
});
const modalEvents: VxeModalListeners = {
  hide() {
    page.title = "新增角色";
    page.value = undefined;
    page.step = 0;
    formData.value = { code: "" };
  },
};
//#endregion

//#region [form]
const formRef = ref<VxeFormInstance>();
const formData = ref<Form<RoleInfo>>({ code: "" });
const formProps = reactive<VxeFormProps<Form<RoleInfo>>>({
  titleAlign: "right",
  titleWidth: 60,
  span: 24,
  items: [
    { field: "code", title: "编码", itemRender: { name: "$input", props: { placeholder: "请输入角色编码" } } },
    { field: "name", title: "名称", itemRender: { name: "$input", props: { placeholder: "请输入角色名称" } } },
    {
      field: "description",
      title: "描述",
      contentClassName: "field-description",
      itemRender: { name: "$textarea", props: { rows: 5, maxlength: 2000, placeholder: "请输入角色描述" } },
    },
  ],
  rules: {
    code: [{ required: true }, { max: 255, message: "角色编码不能超过255个字符" }],
    name: [{ max: 255, message: "角色名称不能超过255个字符" }],
  },
});
//#endregion

//#region [action]
async function open(value?: RoleInfo) {
  if (value) {
    const role = await apiRole.findById<RoleInfo>(value.id);
    if (!role.value) {
      createMessage("warning", "未找到角色，可能已经删除。");
      return;
    }
    page.value = role.value;
    page.title = `编辑角色 - ${role.value.name}(${role.value.code})`;
    formData.value = role.value;
    formData.value.menuIds = role.value.menus?.map((m) => m.id);
  }

  page.show = true;
}
async function next(delta: number) {
  if (delta > 0) {
    const errMap = await formRef.value?.validate();
    if (errMap) return;
  }

  page.step += delta;
}
async function save() {
  const errMap = await formRef.value?.validate();
  if (!errMap) {
    let result;
    if (page.value) {
      result = await apiRole.edit<number>(page.value.id, formData);
    } else {
      result = await apiRole.add<number>(formData);
    }
    if (result) {
      emit("onsaved", result.value);
      close();
    }
  }
}
function close() {
  page.show = false;
}
//#endregion

defineExpose({ open });
</script>

<template>
  <vxe-modal ref="modalRef" v-model="page.show" :="modalProps" @="modalEvents">
    <template #title>{{ page.title }}</template>
    <div class="role-guide">
      <el-steps :active="page.step" process-status="finish" finish-status="success" simple>
        <el-step title="基本信息" :icon="Avatar" />
        <el-step title="功能权限" :icon="Checked" />
        <el-step title="数据权限" :icon="Tools" />
      </el-steps>
      <el-tabs class="tabs-help" v-model="page.step">
        <el-tab-pane :name="0">
          <el-text type="info" size="small">第一步：角色的基本信息。</el-text>
        </el-tab-pane>
        <el-tab-pane :name="1">
          <el-text type="info" size="small">第二步：角色可以查看哪些页面？ 包括页面内的按钮、部件和列表字段。</el-text>
        </el-tab-pane>
        <el-tab-pane :name="2">
          <el-text type="info" size="small">第三步：角色可以管理哪些业务对象？ 以及每个对象的管理范围。</el-text>
        </el-tab-pane>
      </el-tabs>
      <el-tabs class="tabs-panel" v-model="page.step">
        <el-tab-pane :name="0">
          <vxe-form ref="formRef" :="formProps" :data="formData"></vxe-form>
        </el-tab-pane>
        <el-tab-pane :name="1">
          <menu-picker v-model="formData.menuIds" />
        </el-tab-pane>
        <el-tab-pane :name="2"></el-tab-pane>
      </el-tabs>
    </div>
    <template #footer>
      <el-button type="primary" v-show="page.step > 0" @click="next(-1)">上一步</el-button>
      <el-button type="primary" v-show="page.step < 2" @click="next(1)">下一步</el-button>
      <el-button type="warning" v-show="page.step === 2" @click="save">保存</el-button>
      <el-button @click="close">取消</el-button>
    </template>
  </vxe-modal>
</template>

<style lang="scss" scoped>
.role-guide {
  display: flex;
  flex-direction: column;
  gap: 5px;
  height: 100%;

  :deep(.el-tabs__header) {
    display: none;
  }

  .tabs-help {
    .el-tab-pane {
      border-radius: var(--vxe-border-radius);
      background-color: var(--el-fill-color-light);
      padding: 5px 10px;
    }
  }

  .tabs-panel {
    flex: auto;
    overflow-y: auto;

    .vxe-form {
      border-radius: var(--vxe-border-radius);
      background-color: transparent;

      :deep(.field-description) {
        textarea {
          text-indent: 2em;
        }
      }
    }
  }
}
</style>
